<template>
  <div class="face-recognition">
    <div class="header">
      <div class="back-btn" @click="goBack">← 返回</div>
      <div class="title">人脸识别登录</div>
    </div>
    
    <div class="video-container">
      <video ref="video" width="640" height="480" autoplay></video>
      <canvas ref="canvas" width="640" height="480"></canvas>
      
      <!-- 识别状态显示 -->
      <div class="status-overlay" v-if="recognitionStatus">
        <div class="status-message" :class="recognitionStatus">
          {{ statusMessage }}
        </div>
      </div>
      
      <!-- 登录成功提示 -->
      <div v-if="showSuccessToast" class="success-toast">
        {{ toastMsg }}
      </div>
    </div>
    
    <div class="info-panel">
      <div class="info-item">
        <span class="label">检测到的人脸：</span>
        <span class="value">{{ peopleCount }}</span>
      </div>
      <div class="info-item">
        <span class="label">识别状态：</span>
        <span class="value" :class="recognitionStatus">{{ statusMessage }}</span>
      </div>
    </div>
  </div>
</template>
   
<script>
import * as faceapi from 'face-api.js';
import axios from 'axios';
import { useRouter } from 'vue-router';

export default {
  name: 'FaceRecognition',
  data() {
    return {
      isLoaded: false,
      lastDetections: [], // 上一帧检测到的人脸
      peopleCount: 0, // 当前人流量计数
      recognitionStatus: '', // 识别状态：'detecting', 'success', 'failed'
      statusMessage: '正在检测人脸...',
      showSuccessToast: false,
      toastMsg: '',
      router: null,
      detectionInterval: null,
      isProcessing: false, // 防止重复处理
    };
  },
  mounted() {
    this.router = useRouter();
    this.loadModels();
    
    // 监听页面可见性变化
    document.addEventListener('visibilitychange', this.handleVisibilityChange);
  },
  methods: {
    async loadModels() {
      try {
        this.statusMessage = '正在加载模型...';
        await Promise.all([
          faceapi.nets.faceRecognitionNet.loadFromUri('/models'),
          faceapi.nets.faceLandmark68Net.loadFromUri('/models'),
          faceapi.nets.ssdMobilenetv1.loadFromUri('/models'),
        ]);
        this.isLoaded = true;
        this.statusMessage = '模型加载完成，开始检测...';
        this.recognitionStatus = 'detecting';
        this.startVideo();
      } catch (error) {
        console.error('Failed to load models:', error);
        this.statusMessage = '模型加载失败，请刷新页面重试';
        this.recognitionStatus = 'failed';
      }
    },
    
    startVideo() {
      if (navigator.mediaDevices && this.isLoaded) {
        navigator.mediaDevices.getUserMedia({ video: true })
          .then(stream => {
            this.$refs.video.srcObject = stream;
            this.$refs.video.onloadedmetadata = () => {
              this.detectFaces();
            };
          })
          .catch(error => {
            console.error('getUserMedia error:', error);
            this.statusMessage = '无法访问摄像头，请检查权限设置';
            this.recognitionStatus = 'failed';
          });
      }
    },
   
    async detectFaces() {
      const video = this.$refs.video;
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext('2d');
      const detectionOptions = new faceapi.SsdMobilenetv1Options({ minConfidence: 0.9 });
   
      let recentDetections = [];
      const detectionHistoryLength = 5;
   
      this.detectionInterval = setInterval(async () => {
        if (video.readyState === video.HAVE_ENOUGH_DATA && !this.isProcessing) {
          ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
          const detections = await faceapi.detectAllFaces(video, detectionOptions).withFaceLandmarks();
          
          const validDescriptors = detections;
          console.log('检测到的人脸:', validDescriptors.length);
          
          recentDetections.push(...validDescriptors.map(face => face.descriptor));
          recentDetections = recentDetections.slice(-detectionHistoryLength);
          const uniqueDescriptors = Array.from(new Set(recentDetections));
          this.peopleCount = uniqueDescriptors.length;
          
          // 绘制检测结果
          faceapi.draw.drawDetections(canvas, detections);
          faceapi.draw.drawFaceLandmarks(canvas, detections);
          
          // 如果检测到人脸且数量稳定，尝试登录
          if (this.peopleCount > 0 && this.peopleCount <= 2) {
            this.statusMessage = '检测到人脸，正在识别...';
            this.recognitionStatus = 'detecting';
            
            // 延迟一下再处理，确保检测稳定
            setTimeout(() => {
              if (this.peopleCount > 0 && !this.isProcessing) {
                this.handleFaceLogin();
              }
            }, 1000);
          } else if (this.peopleCount === 0) {
            this.statusMessage = '未检测到人脸，请正对摄像头';
            this.recognitionStatus = 'detecting';
          } else {
            this.statusMessage = '检测到多个人脸，请确保只有一个人';
            this.recognitionStatus = 'detecting';
          }
        }
      }, 100);
    },
    
    async handleFaceLogin() {
      if (this.isProcessing) return;
      
      this.isProcessing = true;
      this.statusMessage = '正在验证身份...';
      this.recognitionStatus = 'detecting';
      
      try {
        // 获取当前帧的图像数据
        const canvas = this.$refs.canvas;
        const imageData = canvas.toDataURL('image/jpeg', 0.8);
        
        // 调用后端人脸识别登录API
        const response = await axios.post('http://localhost:3000/users/face-login', {
          faceImage: imageData,
          timestamp: Date.now()
        });
        
        if (response.data.success) {
          // 登录成功
          this.statusMessage = '识别成功！正在登录...';
          this.recognitionStatus = 'success';
          
          // 存储登录token和用户信息
          localStorage.setItem('token', response.data.token);
          localStorage.setItem('userInfo', JSON.stringify(response.data.user));
          
          // 显示成功消息
          this.showSuccessToast = true;
          this.toastMsg = response.data.message || '人脸识别登录成功！';
          
          // 停止检测
          if (this.detectionInterval) {
            clearInterval(this.detectionInterval);
          }
          
          // 延迟跳转到首页
          setTimeout(() => {
            this.stopVideoAndDetection();
            this.router.push('/home');
          }, 1500);
          
                 } else {
           // 登录失败
           this.statusMessage = response.data.message || '人脸识别失败，请重试';
           this.recognitionStatus = 'failed';
           this.isProcessing = false;
           
           // 3秒后重置状态，允许重新尝试
           setTimeout(() => {
             if (this.recognitionStatus === 'failed') {
               this.statusMessage = '未检测到人脸，请正对摄像头';
               this.recognitionStatus = 'detecting';
             }
           }, 3000);
         }
        
             } catch (error) {
         console.error('人脸识别登录失败:', error);
         this.statusMessage = error.response?.data?.message || '网络错误，请重试';
         this.recognitionStatus = 'failed';
         this.isProcessing = false;
         
         // 3秒后重置状态，允许重新尝试
         setTimeout(() => {
           if (this.recognitionStatus === 'failed') {
             this.statusMessage = '未检测到人脸，请正对摄像头';
             this.recognitionStatus = 'detecting';
           }
         }, 3000);
       }
    },
    
    stopVideoAndDetection() {
      // 停止检测
      if (this.detectionInterval) {
        clearInterval(this.detectionInterval);
        this.detectionInterval = null;
      }
      // 停止视频流
      if (this.$refs.video && this.$refs.video.srcObject) {
        this.$refs.video.srcObject.getTracks().forEach(track => {
          track.stop();
          console.log('摄像头已关闭:', track.label);
        });
        this.$refs.video.srcObject = null;
      }
      console.log('人脸识别检测已停止');
    },
    
    goBack() {
      this.stopVideoAndDetection();
      this.router.push('/login');
    }
  },
  
  beforeDestroy() {
    // 清理资源
    this.stopVideoAndDetection();
    
    // 移除事件监听器
    document.removeEventListener('visibilitychange', this.handleVisibilityChange);
  },
  
  // 处理页面可见性变化
  handleVisibilityChange() {
    if (document.hidden) {
      // 页面不可见时暂停检测
      if (this.detectionInterval) {
        clearInterval(this.detectionInterval);
        this.detectionInterval = null;
        console.log('页面不可见，暂停人脸检测');
      }
    } else {
      // 页面重新可见时恢复检测
      if (this.isLoaded && this.$refs.video && this.$refs.video.srcObject) {
        this.detectFaces();
        console.log('页面重新可见，恢复人脸检测');
      }
    }
  },
  
  // 路由离开守卫
  beforeRouteLeave(to, from, next) {
    // 在路由离开前停止摄像头和检测
    this.stopVideoAndDetection();
    next();
  },
};
</script>
   
<style scoped>
.face-recognition {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  position: relative;
  overflow: hidden;
}

/* 背景装饰 */
.face-recognition::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="20" cy="20" r="2" fill="rgba(255,255,255,0.1)"/><circle cx="80" cy="40" r="1.5" fill="rgba(255,255,255,0.1)"/><circle cx="40" cy="80" r="1" fill="rgba(255,255,255,0.1)"/></svg>');
  pointer-events: none;
}

.header {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  position: relative;
  z-index: 10;
}

.back-btn {
  color: #007AFF;
  font-size: 18px;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
}

.back-btn:active {
  background-color: rgba(0, 122, 255, 0.1);
  transform: scale(0.95);
}

.title {
  flex: 1;
  text-align: center;
  font-size: 20px;
  font-weight: 700;
  color: #333;
  margin-right: 40px;
  letter-spacing: 0.5px;
}

.video-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 16px;
  margin: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
}

video, canvas {
  border-radius: 16px;
  width: 100%;
  max-width: 320px;
  height: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.status-overlay {
  position: absolute;
  top: 16px;
  left: 16px;
  right: 16px;
  z-index: 10;
}

.status-message {
  background: rgba(0, 0, 0, 0.85);
  color: white;
  padding: 14px 20px;
  border-radius: 12px;
  text-align: center;
  font-size: 15px;
  font-weight: 600;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}

.status-message.success {
  background: linear-gradient(135deg, rgba(34, 197, 94, 0.95), rgba(22, 163, 74, 0.95));
  border: 1px solid rgba(34, 197, 94, 0.3);
}

.status-message.failed {
  background: linear-gradient(135deg, rgba(239, 68, 68, 0.95), rgba(220, 38, 38, 0.95));
  border: 1px solid rgba(239, 68, 68, 0.3);
}

.info-panel {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  margin: 0 16px 16px;
  padding: 20px;
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 16px;
  color: #666;
  font-weight: 500;
}

.value {
  font-size: 18px;
  font-weight: 700;
  color: #333;
  padding: 8px 16px;
  border-radius: 12px;
  background: rgba(0, 0, 0, 0.05);
  min-width: 80px;
  text-align: center;
}

.value.success {
  color: #22c55e;
  background: rgba(34, 197, 94, 0.1);
  border: 1px solid rgba(34, 197, 94, 0.2);
}

.value.failed {
  color: #ef4444;
  background: rgba(239, 68, 68, 0.1);
  border: 1px solid rgba(239, 68, 68, 0.2);
}

.value.detecting {
  color: #007AFF;
  background: rgba(0, 122, 255, 0.1);
  border: 1px solid rgba(0, 122, 255, 0.2);
}

.success-toast {
  position: fixed;
  left: 50%;
  bottom: 100px;
  transform: translateX(-50%);
  min-width: 280px;
  max-width: 90vw;
  background: linear-gradient(135deg, #22c55e, #16a34a);
  color: #fff;
  text-align: center;
  padding: 18px 24px;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(34, 197, 94, 0.4);
  font-size: 16px;
  font-weight: 600;
  z-index: 9999;
  animation: toast-pop 0.4s ease-out;
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
}

@keyframes toast-pop {
  0% {
    opacity: 0;
    transform: translateX(-50%) translateY(40px) scale(0.8);
  }
  50% {
    transform: translateX(-50%) translateY(-5px) scale(1.05);
  }
  100% {
    opacity: 1;
    transform: translateX(-50%) translateY(0) scale(1);
  }
}

/* 移动端优化 */
@media (max-width: 480px) {
  .header {
    padding: 12px 16px;
  }
  
  .title {
    font-size: 18px;
    margin-right: 32px;
  }
  
  .back-btn {
    width: 36px;
    height: 36px;
    font-size: 16px;
  }
  
  .video-container {
    margin: 12px;
    padding: 12px;
    border-radius: 16px;
  }
  
  video, canvas {
    max-width: 280px;
    border-radius: 12px;
  }
  
  .status-overlay {
    top: 12px;
    left: 12px;
    right: 12px;
  }
  
  .status-message {
    padding: 12px 16px;
    font-size: 14px;
    border-radius: 10px;
  }
  
  .info-panel {
    margin: 0 12px 12px;
    padding: 16px;
    border-radius: 16px;
  }
  
  .info-item {
    padding: 12px 0;
  }
  
  .label {
    font-size: 15px;
  }
  
  .value {
    font-size: 16px;
    padding: 6px 12px;
    min-width: 70px;
  }
  
  .success-toast {
    min-width: 260px;
    padding: 16px 20px;
    font-size: 15px;
    bottom: 80px;
  }
}

/* 小屏幕手机优化 */
@media (max-width: 360px) {
  .header {
    padding: 10px 12px;
  }
  
  .title {
    font-size: 16px;
    margin-right: 28px;
  }
  
  .video-container {
    margin: 8px;
    padding: 8px;
  }
  
  video, canvas {
    max-width: 240px;
  }
  
  .info-panel {
    margin: 0 8px 8px;
    padding: 12px;
  }
  
  .label {
    font-size: 14px;
  }
  
  .value {
    font-size: 15px;
    padding: 4px 8px;
    min-width: 60px;
  }
}

/* 横屏模式优化 */
@media (orientation: landscape) and (max-height: 500px) {
  .face-recognition {
    min-height: 100vh;
  }
  
  .video-container {
    margin: 8px 16px;
    padding: 8px;
  }
  
  video, canvas {
    max-width: 200px;
  }
  
  .info-panel {
    margin: 0 16px 8px;
    padding: 12px;
  }
  
  .success-toast {
    bottom: 60px;
  }
}

/* 高分辨率屏幕优化 */
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
  .status-message,
  .success-toast {
    border-width: 0.5px;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .face-recognition {
    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
  }
  
  .header,
  .video-container,
  .info-panel {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(255, 255, 255, 0.1);
  }
  
  .title {
    color: #fff;
  }
  
  .label {
    color: rgba(255, 255, 255, 0.7);
  }
  
  .value {
    color: #fff;
    background: rgba(255, 255, 255, 0.1);
  }
}
</style>